<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="120px"
    >
      <el-form-item label="平台编号" prop="platformId">
        <el-input
          v-model="queryParams.platformId"
          placeholder="请输入平台编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="店铺编号" prop="storeId">
        <el-input
          v-model="queryParams.storeId"
          placeholder="请输入店铺编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="API配置编号" prop="apiConfigId">
        <el-input
          v-model="queryParams.apiConfigId"
          placeholder="请输入API配置编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="同步任务编号" prop="syncTaskId">
        <el-input
          v-model="queryParams.syncTaskId"
          placeholder="请输入同步任务编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="链路追踪编号" prop="traceId">
        <el-input
          v-model="queryParams.traceId"
          placeholder="请输入链路追踪编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="API类型" prop="apiType">
        <el-select
          v-model="queryParams.apiType"
          placeholder="请选择API类型"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.CROSSBORDER_DATA_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="API名称" prop="apiName">
        <el-input
          v-model="queryParams.apiName"
          placeholder="请输入API名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="API端点" prop="apiEndpoint">
        <el-input
          v-model="queryParams.apiEndpoint"
          placeholder="请输入API端点"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="HTTP方法" prop="httpMethod">
        <el-select
          v-model="queryParams.httpMethod"
          placeholder="请选择HTTP方法"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.CROSSBORDER_HTTP_METHOD)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="请求头" prop="requestHeaders">
        <el-input
          v-model="queryParams.requestHeaders"
          placeholder="请输入请求头"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="请求参数" prop="requestParams">
        <el-input
          v-model="queryParams.requestParams"
          placeholder="请输入请求参数"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="请求体" prop="requestBody">
        <el-input
          v-model="queryParams.requestBody"
          placeholder="请输入请求体"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="响应状态码" prop="responseStatus">
        <el-select
          v-model="queryParams.responseStatus"
          placeholder="请选择响应状态码"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.CROSSBORDER_DATA_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="响应头" prop="responseHeaders">
        <el-input
          v-model="queryParams.responseHeaders"
          placeholder="请输入响应头"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="响应体" prop="responseBody">
        <el-input
          v-model="queryParams.responseBody"
          placeholder="请输入响应体"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker
          v-model="queryParams.startTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker
          v-model="queryParams.endTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="执行时长（毫秒）" prop="duration">
        <el-input
          v-model="queryParams.duration"
          placeholder="请输入执行时长（毫秒）"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="是否成功" prop="success">
        <el-select
          v-model="queryParams.success"
          placeholder="请选择是否成功"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.CROSSBORDER_DATA_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="错误代码" prop="errorCode">
        <el-input
          v-model="queryParams.errorCode"
          placeholder="请输入错误代码"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="错误信息" prop="errorMsg">
        <el-input
          v-model="queryParams.errorMsg"
          placeholder="请输入错误信息"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="重试次数" prop="retryCount">
        <el-input
          v-model="queryParams.retryCount"
          placeholder="请输入重试次数"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="用户IP" prop="userIp">
        <el-input
          v-model="queryParams.userIp"
          placeholder="请输入用户IP"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="用户代理" prop="userAgent">
        <el-input
          v-model="queryParams.userAgent"
          placeholder="请输入用户代理"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['crossborder:platform-api-log:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['crossborder:platform-api-log:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button
            type="danger"
            plain
            :disabled="isEmpty(checkedIds)"
            @click="handleDeleteBatch"
            v-hasPermi="['crossborder:platform-api-log:delete']"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
        row-key="id"
        v-loading="loading"
        :data="list"
        :stripe="true"
        :show-overflow-tooltip="true"
        @selection-change="handleRowCheckboxChange"
    >
    <el-table-column type="selection" width="55" />
      <el-table-column label="日志编号" align="center" prop="id" />
      <el-table-column label="平台编号" align="center" prop="platformId" />
      <el-table-column label="店铺编号" align="center" prop="storeId" />
      <el-table-column label="API配置编号" align="center" prop="apiConfigId" />
      <el-table-column label="同步任务编号" align="center" prop="syncTaskId" />
      <el-table-column label="链路追踪编号" align="center" prop="traceId" />
      <el-table-column label="API类型" align="center" prop="apiType" width="120">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.CROSSBORDER_DATA_TYPE" :value="scope.row.apiType" />
        </template>
      </el-table-column>
      <el-table-column label="API名称" align="center" prop="apiName" />
      <el-table-column label="API端点" align="center" prop="apiEndpoint" />
      <el-table-column label="HTTP方法" align="center" prop="httpMethod" width="100">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.CROSSBORDER_HTTP_METHOD" :value="scope.row.httpMethod" />
        </template>
      </el-table-column>
      <el-table-column label="请求头" align="center" prop="requestHeaders" />
      <el-table-column label="请求参数" align="center" prop="requestParams" />
      <el-table-column label="请求体" align="center" prop="requestBody" />
      <el-table-column label="响应状态码" align="center" prop="responseStatus" />
      <el-table-column label="响应头" align="center" prop="responseHeaders" />
      <el-table-column label="响应体" align="center" prop="responseBody" />
      <el-table-column
        label="开始时间"
        align="center"
        prop="startTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column
        label="结束时间"
        align="center"
        prop="endTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="执行时长（毫秒）" align="center" prop="duration" />
      <el-table-column label="是否成功" align="center" prop="success" />
      <el-table-column label="错误代码" align="center" prop="errorCode" />
      <el-table-column label="错误信息" align="center" prop="errorMsg" />
      <el-table-column label="重试次数" align="center" prop="retryCount" />
      <el-table-column label="用户IP" align="center" prop="userIp" />
      <el-table-column label="用户代理" align="center" prop="userAgent" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['crossborder:platform-api-log:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['crossborder:platform-api-log:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <PlatformApiLogForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { isEmpty } from '@/utils/is'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { DICT_TYPE, getIntDictOptions, getStrDictOptions, getBoolDictOptions } from '@/utils/dict'
import { PlatformApiLogApi, PlatformApiLogVO } from '@/api/crossborder/platformapilog'
import PlatformApiLogForm from './PlatformApiLogForm.vue'

/** 跨境电商平台API调用日志 列表 */
defineOptions({ name: 'PlatformApiLog' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<PlatformApiLogVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  platformId: undefined,
  storeId: undefined,
  apiConfigId: undefined,
  syncTaskId: undefined,
  traceId: undefined,
  apiType: undefined,
  apiName: undefined,
  apiEndpoint: undefined,
  httpMethod: undefined,
  requestHeaders: undefined,
  requestParams: undefined,
  requestBody: undefined,
  responseStatus: undefined,
  responseHeaders: undefined,
  responseBody: undefined,
  startTime: [],
  endTime: [],
  duration: undefined,
  success: undefined,
  errorCode: undefined,
  errorMsg: undefined,
  retryCount: undefined,
  userIp: undefined,
  userAgent: undefined,
  createTime: [],
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await PlatformApiLogApi.getPlatformApiLogPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await PlatformApiLogApi.deletePlatformApiLog(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 批量删除跨境电商平台API调用日志 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await PlatformApiLogApi.deletePlatformApiLogList(checkedIds.value);
    message.success(t('common.delSuccess'))
    await getList();
  } catch {}
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: PlatformApiLogVO[]) => {
  checkedIds.value = records.map((item) => item.id);
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await PlatformApiLogApi.exportPlatformApiLog(queryParams)
    download.excel(data, '跨境电商平台API调用日志.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>